<script setup lang="ts">
import Terminal from 'vue-web-terminal'
import { computed, onMounted, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useToolStore } from '../stores/tool'

const { processing, existsSchedule } = storeToRefs(useToolStore())
declare global {
  interface Window {
    pywebview: { api: any },
    debug: (text: string, type: any) => void
  }
}

const downloadHolidays = () => {
  // 下载股票数据
  if (processing.value) {
    alert('有一次性任务正在进行，请稍后再试！')
    return
  }
  processing.value = true as any
  window.pywebview.api.downloadHolidays().then(data => {
    processing.value = false as any
  })
  //
}

const downloadStocksTotalInfo = () => {
  // 下载股票数据
  if (processing.value) {
    alert('有一次性任务正在进行，请稍后再试！')
    return
  }
  processing.value = true as any
  window.pywebview.api.downloadStocksTotalInfo().then(data => {
    processing.value = false as any
  })
  //
}
const downloadStocksDailySingle = () => {
  // 下载股票数据
  if (processing.value) {
    alert('有一次性任务正在进行，请稍后再试！')
    return
  }
  if (symbol.value.length != 6) {
    alert(`${symbol.value}不是有效的股票代码，请检查`)
    return
  }
  processing.value = true as any
  window.pywebview.api.downloadStocksDailySingle(symbol.value).then(data => {
    processing.value = false as any
  })
  //
}
const downloadStocksDailyAll = () => {
  // 下载股票数据
  if (!processing.value) {
    processing.value = true as any
    window.pywebview.api.downloadStocksDailyAll().then(data => {
      processing.value = false as any
    })
  } else {
    alert('有一次性任务正在进行，请稍后再试！')
  }

  //
}

const autoUpdate = () => {
  if (processing.value) {
    alert('有一次性任务正在进行，请稍后再试！')
    return
  }
  if (!existsSchedule.value) {
    existsSchedule.value = true as any
    appendText('启动定时任务...', 'info')
    window.pywebview.api.autoUpdate().then(data => {
    })
  } else {
    appendText('已经存在定时任务', 'success')
  }
}


const printWindow = () => {
  if (processing.value) {
    alert('有一次性任务正在进行，请稍后再试！')
    return
  }
  processing.value = true as any
  window.pywebview.api.printWindow().then(data => {
    processing.value = false as any
  })
}

const tag = {
  'info': '信息',
  'warning': '警告',
  'success': '成功',
  'error': '错误',
  'system': '系统'
}

/**
 * 在输出终端上打印程序执行信息，为了暴露给python调用，需要将该方法暴露给window对象
 */
const appendText = (text: string, type: keyof typeof tag) => {
  if (terminalRef.value) {
    terminalRef.value.pushMessage({
      class: type, // 可取值warning info success error system
      tag: tag[type],
      content: text
    })
  }
}
const terminalRef = ref()


function onExecCmd(key, command, success, failed) {
  if (key === 'fail') {
    failed('Something wrong!!!')
  } else {
    let allClass = ['success', 'error', 'system', 'info', 'warning']

    let clazz = allClass[Math.floor(Math.random() * allClass.length)]
    success({
      type: 'normal',
      class: clazz,
      tag: '成功',
      content: command
    })
  }
}

onMounted(() => {
  // if (terminalRef.value) {
  //   terminalRef.value.pushMessage({
  //     class: 'info', // 可取值warning info success error system
  //     tag: 'INFO', content: '警告信息'
  //   })
  //   // terminalRef.value.fullscreen() 最大化窗口
  // }
  window.debug = appendText // throttle(appendText, 100)
})

const symbol = ref('000001')
</script>

<template>
  <div class="container1 flex w-full h-full">
    <div class="leftDiv h-full bg-blue-100">
      <div class="innerLeftDiv w-full grid grid-cols-1">
        <div class="text-center">
          <button class="button m-2 h-10" @click="downloadHolidays">下载假期数据</button>
          <button class="button m-2 h-10" @click="downloadStocksTotalInfo">下载股票列表</button>
          <button class="button m-2 h-10" @click="downloadStocksDailyAll">下载所有股票日线数据
          </button>
        </div>

        <div class="border-emerald-300 border-2 text-center m-2">
          <label>股票代码：</label>
          <input type="text" v-model="symbol">
          <button class="button m-2 h-10" @click="downloadStocksDailySingle">下载股票日线数据
          </button>
        </div>
        <button class="button m-2 h-10" @click="autoUpdate">自动更新</button>
        <!--      <button class="button m-2 h-10" @click="printWindow">自动更新</button>-->
      </div>
    </div>
    <div class="rightDiv h-full bg-green-100">
      <terminal ref="terminalRef" name="terminal" @exec-cmd="onExecCmd" theme="light" context="Terminal"
                :show-header="true" title="终端控制台" :log-size-limit="1000"></terminal>
    </div>
  </div>
</template>

<style scoped lang="postcss">
@tailwind base;
@tailwind components;
@tailwind utilities;
.container1 {
  flex-direction: row;
}

.leftDiv {
  flex-basis: 60%;
  flex-wrap: wrap; /* 容器属性：当容器中的元素一行放不下时，是否换行 */
  align-content: flex-start; /* 容器属性：当换行时，元素的对齐方式，尽量往前排 */
  flex-direction: column;
}

.rightDiv {
  min-width: 600px;
  flex-basis: 40%;
}

.button {
  display: inline-block;
  padding: 2px 2px;
  font-size: 16px;
  cursor: pointer;
  text-align: center;
  text-decoration: none;
  outline: none;
  color: #fff;
  background-color: rgb(16, 185, 214);
  border: none;
  border-radius: 5px;
  box-shadow: 0 9px #999;
  flex-basis: 100px; /* flex item计算元素宽度的基础宽度 */
  min-width: 200px; /* flex item元素宽度由flex-basis确定，该设置相当于限制了元素的最小宽度 */
  flex-grow: 1;
  flex-shrink: 0;
}

.button:hover {
  background-color: #1795bb;
}

.button:active {
  background-color: #1795bb;
  box-shadow: 0 5px #666;
  transform: translateY(4px);
}


</style>